package com.yanjue.service.task;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yanjue.common.entity.UserBookshelf;
import com.yanjue.mapper.UserBookshelfMapper;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;

/**
 * 书架同步任务
 */

@NoArgsConstructor
public class UserBookshelfTask implements Runnable {
    @Resource
    private ExecutorService userBookshelfQueueThreadPool;

    private static final Logger LOGGER = LoggerFactory.getLogger(UserBookshelfTask.class);
    /** 处理类型：1.新增 2.修改 3.删除 */
    private Integer syncType;
    private UserBookshelf bookshelf;
    private UserBookshelfMapper bookshelfMapper;
    private Integer userId;

    public UserBookshelfTask(Integer syncType, UserBookshelf bookshelf, UserBookshelfMapper bookshelfMapper, Integer userId) {
        this.syncType = syncType;
        this.bookshelf = bookshelf;
        this.bookshelfMapper = bookshelfMapper;
        this.userId = userId;
    }

    private int retryCount = 0;

    @Override
    public void run() {
        try{
            if (1 == syncType) {
                this.bookshelf.setUserId(this.userId);
                this.bookshelfMapper.insert(this.bookshelf);
            } else if (2 == syncType) {
                this.bookshelf.setUserId(this.userId);
                //通过 userid 和 bookId 更新
                LambdaUpdateWrapper<UserBookshelf> queryWrapper = new LambdaUpdateWrapper<>();
                queryWrapper.eq(UserBookshelf::getUserId,bookshelf.getUserId())
                        .eq(UserBookshelf::getBookId,bookshelf.getBookId());
                //只更新不为null 的字段
                if (bookshelf.getLastChapterId() != null){
                    queryWrapper.set(UserBookshelf::getLastChapterId,bookshelf.getLastChapterId());
                }
                if (bookshelf.getLastReadTime() != null){
                    queryWrapper.set(UserBookshelf::getLastReadTime,bookshelf.getLastReadTime());
                }
                //执行更新
                this.bookshelfMapper.update(queryWrapper);
            } else if (3 == syncType) {
                this.bookshelfMapper.deleteById(this.bookshelf.getId());
            }
        } catch (Exception ex){
            handleRetryOrLog(ex);
        }
    }

    private void handleRetryOrLog(Exception ex) {
        if (retryCount < 3) {
            retryCount++;
            userBookshelfQueueThreadPool.submit(this); // 重新提交任务
        } else {
            LOGGER.error("书架同步失败，已达最大重试次数。类型：{}，用户：{}，书籍：{}，异常：{}",
                    syncType, userId, bookshelf.getBookId(), ex);
        }
    }
/*
    public UserBookshelfTask(){}

    public UserBookshelfTask(Integer syncType, UserBookshelf bookshelf, UserBookshelfMapper bookshelfMapper, Integer userId) {
        this.syncType = syncType;
        this.bookshelf = bookshelf;
        this.bookshelfMapper = bookshelfMapper;
        this.userId = userId;
    }*/
}
